import { udp, useAsyncEffect } from '@cscec/udp-mobile-ui';
import { queryDetail, queryDetails } from './service';
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import BellaHeader from '@/components/header';
import {  Toast } from 'antd-mobile';
import styles from './index.less';
import { Card, Col, Row, Space, Button, message } from 'antd';
import { AudioOutlined, PlayCircleOutlined, SoundOutlined, XFilled } from '@ant-design/icons';
import { useSpeechService } from '@/util';
import { Uphistory } from '../Schme/service';
import ItemRead from '@/components/itemRead';
import ItemResult from '@/components/itemResult';
import { updateScore } from '../Textbook/service';
import { useAudioPlay } from '@/hooks/useAudioPlay';
import { recognizeSpeechByFile } from '@/servers/baiduSpeechService';

const PageList: React.FC = () => {
  const { title, id } = udp.getQueryValue()
  const [value, setValue] = useState<any>({})
  const [hidden, setHidden] = useState(false)
  const [mess, setMess] = useState<any>([]);
  const [cardList, setCardList] = useState<any>([]);
  const totalSentences = cardList.length;
  const [card, setCard] = useState(1);
  const [imgsrc, setImgSrc] = useState("")//图片内容
  const [currentCard, setCurrentCard] = useState(1)
  const [totalCards, setTotalCards] = useState(1)//准备学习总数||总句子数目
  const [cardSort, setCardSort] = useState(0)//准备学习序号
  const containerRef = useRef<HTMLDivElement>(null);//ref用于计算页面高度，实现上线滚动
  const latestItemRef = useRef<HTMLDivElement>(null);
  //录音次数
  const [recordItem,setRecordItem]=useState(0)
  const [readText,setReadText] = useState('')

  // 控制弹窗是否出现
  const [showModal, setShowModal] = useState(false);
  // 弹窗内容
  const [modalContent, setModalContent] = useState<any>("");
  const { startRecording, stopRecording, compatibility } = useSpeechService();

  const { isPlaying, isLoading, playAudio, stopAudio } = useAudioPlay({
    //per:'4189',
    spd: '3'
  });


  useEffect(() => {
    queryDetail({ id: id, articleType: 1 }).then((res) => {
      setValue(res)
    })
  }, [id])


  useEffect(() => {
    if (value.tbSentencesVos && value.tbSentencesVos.length > 0) {
      setMess(value.tbSentencesVos)
    }
  }, [value])

  useAsyncEffect(async () => {
    if (mess.length && mess.length > 0) {
      if (currentCard > mess.length) {
        Uphistory({
          textbookId: value.textbookId,
          unitId: value.unitId,
          topicId: value.topicId,
          exerciseId:value.id,
          completionStatus: 2, studyFlag: 1
        }).then((rt) => {
          udp.message('当前主题文章已经学习完毕!')
          udp.close()
        })
      } else {
        const result = await queryDetails({ masterId: mess[Number(currentCard) - 1].masterId, cardNo: currentCard })
        setCardList(result)
      }
    }
  }, [mess, currentCard])

   /**
   * 开始录音处理
   */
  const handleStartRecording = async (index) => {
    try {
      // 添加兼容性检查
    if (!compatibility.recording) {
      Toast.show('您的浏览器不支持录音功能');
      return;
    }
    
    if (!compatibility.mimeType) {
      Toast.show('无法找到支持的音频格式');
      return;
    }
    if(cardList[index].isRead){
      handleStopRecording(index)
      return
    }
      setRecordItem(pr=>pr+1)
      await startRecording();
      const ttstr = udp.deepCopy(cardList)
      ttstr[index].isRead = true,//isRead用于纪录每条数据的录音状态
      setCardList(ttstr)
    } catch (error) {
      Toast.show({
        content: `无法开始录音: ${error}`,
        position: 'top'
      });
    }
  };

   /**
   * 停止录音并处理匹配
   */
  const handleStopRecording = async (index) => {
    try {
      const audioBlob = await stopRecording();
      recognizeSpeechByFile(audioBlob).then((rt:any)=>{
        if(rt.code==200){
          const url = URL.createObjectURL(audioBlob);
          const ttstr = udp.deepCopy(cardList)
          ttstr[index].result = rt.data;
          ttstr[index].userRead = url,//userRead用于纪录每条数据的录音
          ttstr[index].isRead = false,//isRead用于纪录每条数据的录音状态
          setCardList(ttstr)
        }else{
          message.error('语音识别失败请重试')
        }
      })
    } catch (error) {
      Toast.show({
        content: `录音处理失败: ${error}`,
        position: 'top'
      });
    }
  };

  // 播放录音
  const playRecording = (userRead,index) => {
    if (userRead) {
      const audio = new Audio(userRead);
      audio.play()
      setShowModal(true);
      setModalContent("播放你的声音");
    } else {
      Toast.show({ content: '没有可播放的录音', position: 'bottom' });
    }
  };


  const [cardCount, setCardCount] = useState(1);
  // 当数据更新后，滚动到最新数据的位置（中间）
  useLayoutEffect(() => {
    if (latestItemRef.current && containerRef.current) {
      const container = containerRef.current;
      const item = latestItemRef.current;
      // 计算目标滚动位置：使最新的一项在容器中间
      const targetScrollTop = item.offsetTop - (container.offsetHeight / 2) + (item.offsetHeight / 2);
      container.scrollTo({
        top: targetScrollTop,
        behavior: 'smooth' // 可选，平滑滚动
      });
    }
  }, [cardCount]);


  // 增加卡片数量的函数
  const increaseCards = async () => {
    if (cardCount >= cardList.length) {//翻页
      console.log(recordItem)
      const result = updateScore({//异步一下，优先翻页
        unitId:value.unitId,
        type:1,
        flag:recordItem>1?0:1
      })
      setCardSort(0)
      setCard(card + 1)
      setCurrentCard(currentCard + 1)
      setHidden(false)
      setCardCount(1)
      setRecordItem(0)//翻页时，设置回true
    } else {//增加卡片
      setCardSort(cardSort + 1)
      setCardCount(prevCount => prevCount + 1);
      //出现新卡片自动播放
      debouncedSpeak(cardList[cardCount].name)
    }
  };

  useEffect(() => {
    const imgList = value?.tbSentencesVos
    if (imgList && imgList.length > 0) {
      const totalNum = imgList?.length
      setTotalCards(totalNum)
      setImgSrc(imgList[card - 1]?.imgUrl)
      //setImgTitle(`对话卡片${imgList[card - 1]?.cardNo}`)
    }

  }, [value, card])
  // 防抖函数实现
  function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
      const later = () => {
        clearTimeout(timeout);
        func(...args);
      };
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
    };
  }

  // 创建防抖的speak方法（800ms防抖时间）
  const debouncedSpeak = debounce((text) => {
    setReadText(text)
     playAudio(text)
    setShowModal(true);
    setModalContent("正在播放句子");
  }, 800);


  useEffect(() => {
    // 设置一个定时器，在指定时间后隐藏消息
    const timer = setTimeout(() => {
      setShowModal(false);
    }, 3000);

    // 返回一个清理函数，用于清除定时器，防止内存泄漏
    return () => clearTimeout(timer);
  }, [3000, showModal]); // 依赖项中包含duration，这样当duration变化时也会重新设置定时器




  return (
    <div ref={containerRef} style={{ height: '100vh', overflow: 'auto' }}>
      <BellaHeader title={title} onMain={() => { udp.open('/BellaEnglish') }} />
      {
        hidden ?
          <div>
            <div className={styles["header"]}>
              {/* 进度信息 */}
              <Row justify="space-between" className={styles["navigation-header"]}>
                <Col>
                  <div className={styles["card-label"]}>
                    <span className={styles["label-text"]}>卡片</span>
                    {
                      totalCards > 0 && (
                        <span className={styles["label-count"]}>{currentCard}/{totalCards}</span>
                      )
                    }
                  </div>
                </Col>
                <Col>
                  <div className={styles["card-label"]}>
                    <span className={styles["label-text"]}>句子</span>
                    {
                      totalSentences > 0 && (
                        <span className={styles["label-count"]}>{cardSort}/{totalSentences}</span>
                      )
                    }
                  </div>
                </Col>
              </Row>
              {/* 进度圆点 */}
              <div className={styles["button-container"]}>
                {[...Array(totalCards)].map((_, index) => (
                  <button
                    key={index}
                    className={card === index + 1 ? styles["circle-button-active"] : styles["circle-button"]}
                    onClick={() => {
                      setCard(index + 1)
                      setCurrentCard(index + 1)
                      setHidden(false)
                      setCardCount(1)
                    }
                    }
                  >
                    {index + 1}
                  </button>
                ))}
              </div>
              {/* 图片内容 */}
              <Card className={styles["title-card"]}
                //title={imgTitle}
                cover={
                  <img
                    src={imgsrc}
                  />
                }
                styles={{
                  title: {
                    color: '#a7acef', display: "flex", justifyContent: "center"
                  },
                  body: {
                    padding: '0px'
                  }
                }}>

              </Card>
            </div>
            {Array.from({ length: cardCount }, (_, index) => {
              const isLast = index === cardCount - 1;
              return <Card ref={isLast ? latestItemRef : null} className={styles["titles-card"]}>
                <div className={styles['sentense']}>
                  <ItemRead value={cardList[index]?.name} isPlay={isPlaying} readText={readText} />
                </div>
                  {cardList[index].result?<ItemResult value={cardList[index]?.name} 
                   label={cardList[index].result} />:<></>}
                <div className={styles["phrase-controls"]}>
                  <Space size="middle">
                    <Button
                      type="default"
                      shape="circle"
                      icon={<SoundOutlined style={{ color: "#a7acef" }} />}
                      className={styles["control-button"]}
                      onClick={() => {
                        //handleSpeak(cardList[index]?.name)
                        debouncedSpeak(cardList[index]?.name)
                      }}
                    />
                    <Button
                      type="default"
                      shape="circle"
                      icon={
                        cardList[index].isRead ==true?
                          <XFilled style={{ color: "red" }} />
                          : <AudioOutlined style={{ color: "#a7acef" }} />
                      }
                      className={styles["control-button"]}
                      onClick={() => {
                        handleStartRecording(index)
                        //startRecording(index)
                      }}
                      disabled={!navigator.mediaDevices}
                    />
                    <Button
                      type="default"
                      shape="circle"
                      icon={<PlayCircleOutlined style={{ color: "#a7acef" }} />}
                      className={styles["control-button"]}
                      onClick={()=>{
                        playRecording(cardList[index].userRead,index)
                      }}
                    />
                  </Space>
                </div>
              </Card>
            })}
            {/* 按钮信息 */}
            <div className={styles["actions"]}>
              <Button
                className={styles["continue-button"]}
                style={{
                  background: "rgb(167 172 239)",
                  color: "#ffffff"
                }}
                //className={cardCount >= totalSentences? styles["card-button-disabled"] :styles["continue-button"]}
                block
                shape='round'
                onClick={increaseCards}>Next</Button>
            </div>
          </div>
          : <>
            <div className={styles["header"]}>
              {/* 进度信息 */}
              <Row justify="space-between" className={styles["navigation-header"]}>
                <Col>
                  <div className={styles["card-label"]}>
                    <span className={styles["label-text"]}>卡片</span>
                    {
                      totalCards > 0 && (
                        <span className={styles["label-count"]}>{currentCard}/{totalCards}</span>
                      )
                    }
                  </div>
                </Col>
                <Col>
                  <div className={styles["card-label"]}>
                    <span className={styles["label-text"]}>准备学习</span>
                    {/* {
                      totalSentences > 0 && (
                        <span className={styles["label-count"]}>{cardSort}/{totalSentences}</span>
                      )
                    } */}
                  </div>
                </Col>


              </Row>
              {/* 进度圆点 */}
              <div className={styles["button-container"]}>
                {[...Array(totalCards)].map((_, index) => (
                  <button
                    key={index}
                    //className={styles[`circle-button ${card === index + 1 && 'active'}`]}
                    className={card === index + 1 ? styles["circle-button-active"] : styles["circle-button"]}
                    onClick={() => {
                      setCard(index + 1)
                      setCurrentCard(index + 1)
                      // isReady(true)
                    }
                    }
                  >
                    {index + 1}
                  </button>
                ))}
              </div>
              {/* 图片内容 */}
              <Card className={styles["title-card"]}
                //title={imgTitle}
                cover={
                  <img
                    src={imgsrc}
                  />
                }
                styles={{
                  title: {
                    color: '#a7acef', display: "flex", justifyContent: "center"
                  },
                  body: {
                    padding: '0px'
                  }
                }}>

              </Card>
            </div>
            {/* 按钮信息 */}
            <div className={styles["actions"]}>
              <Button
                className={styles["continue-button"]}
                block
                shape='round'
                style={{
                  backgroundColor:'#a7acef',
                  color:'#ffffff'
                }}
                onClick={() => {
                  setHidden(true)
                  setCardSort(1)
                  //第一个卡片出来，自动播放
                  if (cardList[0].name) {
                    debouncedSpeak(cardList[0].name)
                  }
                }}>Start<PlayCircleOutlined/></Button>
            </div>
          </>
      }
      <div className={showModal ? styles['modal-active'] : styles['modal']}>
        {modalContent}
      </div>
    </div >
  );
};
export default PageList;
